var express = require('express');
var router = express.Router();
var User = require('../model/user.js');
var PW = require('png-word');
var pw = new PW();
var R = require('random-word');

/* GET users listing. */
router.get('/', function(req, res, next) {
    res.locals.user = req.session.user;
    res.send("index");
});

//退出
router.get('/logout', function(req, res){
    req.session.user = undefined;
    return res.redirect("/");
})

//登录
router.post('/login',async function(req, res){
    const {loginname, password, vimg} = req.body;
    let username = "";
    let message = "";
    if(vimg == ""|| vimg == undefined) {
        message = "请输入验证码！";
    }
    else{
        console.log(req.session.vimg);
        if(req.session.vimg === vimg) {
            const user = await User.findOne({'loginname':loginname});
            if(user)
            {
                if(user.password === password)
                {
                    req.session.user = {loginname: loginname};
                    username = loginname;
                }
                else
                {
                    message = "密码错误，请重新输入！";
                }
            }
            else{
                message = "用户不存在！";

            }
        }
        else{
            message = "验证码错误，请重新输入！";

        }
    }
    res.send({username, message});
})

//注册
router.post('/reg', async function(req, res){
    const {loginname , password , confirm, vimg} = req.body;
    let username = "";
    let message = "";

    if(vimg == "" || vimg == undefined)
    {
        message ="请输入验证码！";
    }
    else
    {
        if(req.session.vimg === vimg) {
            let user = await User.findOne({'loginname':loginname});
            if(user)
            {
                let message = "用户名已存在"
            }
            else
            {
                //注册成功
                const newUser = new User({
                    loginname,
                    password,
                    confirm
                })
                await newUser.save();
                username = loginname;
            }
        }
        else{
            message ="验证码错误，请重新输入！";
        }
    }
    return res.send({username, message});
})

router.get('/vimg', function(req, res){
    var r = new R("1234567890");
    req.session.vimg = r.random(3);
    pw.createReadStream(req.session.vimg).pipe(res);
})

module.exports = router;
